package com.zhw.filter;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.zhw.Util.JwtUtils;
import com.zhw.pojo.Result;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

//@WebFilter("/*")
@Slf4j
public class loginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("filter过滤器");
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //1、获取请求的url
        String url = request.getRequestURI();

        //2、判断是否为登录操作，如果为登录操作就执行放行操作
        if (url.contains("login")){
            log.info("登录操作，放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //3、获取请求头中的令牌 token
        String jwt = request.getHeader("token");
        //4、判断令牌是否存在，如果不存在，那么就返回错误结果
        if (!StringUtils.hasLength(jwt)){
//            令牌不存在，返回错误的信息
            log.info("不存在的令牌");
            Result error = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(error);
            response.getWriter().write(jsonString);
            return;
        }
        //5、判断令牌是否有效，无效则返回错误结果
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            Result error = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(error);
            response.getWriter().write(jsonString);
            return;
        }
        //6、通过上面层层筛选，判断令牌有效的，那么就执行放行操作

        filterChain.doFilter(request,response);



    }
}
